package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.ObjectUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class WechatServiceImpl implements WeChatService {
    @Value("${zzyl.wechat.appId}")
    private String appId;
    @Value("${zzyl.wechat.appSecret}")
    private String secret;
    private static final String URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token";
    private static final String PHONE_URL="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    @Override
    public String getOpenId(UserLoginRequestDto userLoginRequestDto) {
        //1.appid + secret + code调取第三方微信官方去获取openid
        String code = userLoginRequestDto.getCode();
        HashMap<String, Object> requestParam = getParam();
        requestParam.put("js_code", code);
        requestParam.put("grant_type", "authorization_code");
        String result = HttpUtil.get(URL, requestParam);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("openid");
    }

    private HashMap<String, Object> getParam() {
        HashMap<String, Object> requestParam = new HashMap<>();
        requestParam.put("appid", appId);
        requestParam.put("secret", secret);

        return requestParam;
    }

    @Override
    public String getPhoneNum(UserLoginRequestDto userLoginRequestDto) {
        //1.获取access_token
        HashMap<String, Object> param = getParam();
        param.put("grant_type", "client_credential");
        String result = HttpUtil.get(TOKEN_URL, param);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String access_token = jsonObject.getStr("access_token");
        //2.获取手机号
        HashMap<String, Object> param1 = new HashMap<>();
        String code = userLoginRequestDto.getPhoneCode();
        param1.put("code",code);

        String result1 = HttpUtil.post(PHONE_URL+access_token, JSONUtil.toJsonStr(param1));

        JSONObject jsonObject1 = JSONUtil.parseObj(result1);

        if(jsonObject1.getInt("errcode")!=0){
            throw new RuntimeException(jsonObject1.getStr("errmsg"));
        }
        JSONObject phoneInfo = (JSONObject) jsonObject1.get("phone_info");
        return phoneInfo.getStr("phoneNumber");
    }
}
